package net.core.service.csv;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExpCsv {

	private static final char delimiter = ',';
	private static final String charset = "gbk";

	/**
	 * 
	 * @Title: WriteCsv
	 * @param lt
	 *            导出结果集
	 * @param titleId
	 *            列字段
	 * @param titleName
	 *            表头字段名称
	 * @param fileName
	 *            文件名称 带路径全名称 。如D:/log/debug/123.csv
	 * @return void
	 * @description
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-11-7 下午03:26:17
	 */
	public static void WriteCsv(List<Map<String, String>> lt, String titleId, String titleName, String fileName) {

		String[] titleIds = titleId.split(";;");
		String[] titleNames = titleName.split(";;");

		CsvWriter wr = null;
		try {
			wr = new CsvWriter(fileName, delimiter, Charset.forName(charset));
			wr.writeRecord(titleNames);// 表头

			if (titleIds != null && titleIds.length > 0) {
				for (int j = 0; j < lt.size(); j++) {
					HashMap<String, String> map = (HashMap<String, String>) lt.get(j);
					String[] contents = new String[titleIds.length+1];
					contents[0] = String.valueOf(j);//序号
					for (int m = 0; m < titleIds.length; m++) {
						contents[m+1] = getValue(map.get(titleIds[m]), " ");
					}
					wr.writeRecord(contents);// 表头
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (wr != null) {
				wr.close();
			}
		}
	}

	/*
	 * 对象 null 空串 处理
	 */
	public static String getValue(Object obj, String defStr) {
		if (obj == null || ("").equals(obj)) {
			return defStr;
		} else {
			return obj.toString().trim();
		}
	}
}
